knitr::opts_chunk$set(fig.width=5, fig.height=5) 

rm(list=ls())



options(scipen=999)

library(tidyverse)
library(broom)
library(lubridate)
library(stargazer)
library(interflex)
library(reshape2)
pkgs <- c("dplyr", "ggplot2", "stargazer", "car", "tidyverse", "extrafont", "haven", "coefplot", "plotrix", "sensemakr", "cjoint")
# A function to load all above packages. Install if they have not been installed.
usePackage <- function(p){
  for (pkg in p){
    if (!is.element(pkg, installed.packages()[,1]))
      install.packages(pkg, dep = TRUE, repos = "https://cloud.r-project.org/")
    require(pkg, character.only = TRUE)
  }
}
usePackage(pkgs)


d0 <- read.csv("Study 5 Data.csv")

d0$LeastLikedTreatment <- ifelse(d0$LeastLiked_QD == "", 1, 0)





d0$Conjoint1_SC <- ifelse(d0$Conjoint1_SC == 1, 1, 0)
d0$Conjoint2_SC <- ifelse(d0$Conjoint2_SC == 1, 1, 0)
d0$Conjoint3_SC <- ifelse(d0$Conjoint3_SC == 1, 1, 0)



d0$Republican <- 0
d0$Republican[d0$Demo_party_SC == 2 | d0$Demo_partylean_SC == 2] <- 1
d0$Democrat <- 0
d0$Democrat[d0$Demo_party_SC == 1 | d0$Demo_partylean_SC == 1] <- 1

d0$Independent <- as.numeric(ifelse(d0$Democrat == 1 | d0$Republican == 1, 0, 1))

d0$Education <- as.numeric(d0$Demo_education_SC)

d0$CollegeEducation0 <- ifelse(d0$Education > 4, 1, 0)

d0$PriorGovtJob0 <- as.numeric(grepl("16", d0$Demo_jobprior_MS))


d0$StrongIdeologue0 <- ifelse(d0$Demo_ideo_SC == -2 | d0$Demo_ideo_SC == 2, 1, 0)



d1 <- subset(d0, d0$Independent ==0 & d0$DistributionChannel == "anonymous")

d1$InParty <- d1$Inparty2_QD

summary(d1$CollegeEducation0)

demos <- read.csv("Study 5 Demographics.csv")
demos$participantId <- demos$ParticipantId

m <- merge(x = demos, y = d1, by = "participantId")

summary(as.factor(m$Race))
summary(as.factor(m$Sex))
summary(as.factor(m$Age))
summary(as.factor(m$Democrat))
summary(as.factor(m$Republican))
summary(as.factor(m$Household.Income))
summary(as.factor(m$Education.x))



### DESCRIPTIVES

summary(as.factor(d0$Civillib_GR_hate))
summary(as.factor(d0$Civillib_GR_legal))
summary(as.factor(d0$Civillib_GR_speech))
summary(as.factor(d0$Civillib_GR_read))
summary(as.factor(d0$Civillib_GR_argue))
summary(as.factor(d0$Civillib_rally_SC))



summary(as.factor(d0$Civillib_min_SC))
summary(as.factor(d0$Civillib_const_SC))
summary(as.factor(d0$Civillib_speech_SC))


d0$Party <- ifelse(d0$Democrat == 1, "Democrat",
                   ifelse(d0$Republican == 1, "Republican", NA))

civillib_min_SC_summary <- table(d0$Party, d0$Civillib_min_SC) / rowSums(table(d0$Party, d0$Civillib_min_SC)) * 100

# Calculate percentages for Civil Liberties in the context of Constitutionality at the Supreme Court level
civillib_const_SC_summary <- table(d0$Party, d0$Civillib_const_SC) / rowSums(table(d0$Party, d0$Civillib_const_SC)) * 100

# Calculate percentages for Civil Liberties concerning Speech at the Supreme Court level
civillib_speech_SC_summary <- table(d0$Party, d0$Civillib_speech_SC) / rowSums(table(d0$Party, d0$Civillib_speech_SC)) * 100


# New data based on the provided summaries
data <- data.frame(
  Measure = rep(c("Majority Ignores Minority", "Majority Violates Constitution", "Majority Bans Speech"), each = 6),
  Party = rep(c("Democrat", "Republican"), times = 9),
  Category = rep(c(0, 0.5, 1), times = 6),
  Value = c(
    # Majority Ignores Minority
    6.333973, 12.667946, 80.998081, # Democrat
    10.563380, 18.075117, 71.361502, # Republican
    
    # Majority Violates Constitution
    35.89251, 22.64875, 41.45873, # Democrat
    11.03286, 15.02347, 73.94366, # Republican
    
    # Majority Bans Speech
    11.90019, 21.30518, 66.79463, # Democrat
    16.19718, 14.08451, 69.71831 # Republican
  )
)

# Transforming the data into a tidy format
data <- data %>%
  mutate(Category = factor(Category, levels = c(1, 0.5, 0), labels = c("No", "Neither", "Yes")),
         Measure = factor(Measure, levels = c("Majority Ignores Minority", "Majority Violates Constitution", "Majority Bans Speech")))

# Plotting with updated adjustments
todaypartisans<-ggplot(data, aes(x = Category, y = Value, fill = Party)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  facet_wrap(~Measure, scales = "free") +
  scale_fill_manual(values = c("Democrat" = "blue", "Republican" = "red")) +
  scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, by = 10)) +
  labs(title = "General Population Comparison of Political Party Positions",
       x = "Category",
       y = "Percentage",
       fill = "Party") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        legend.position = "bottom",
        plot.title = element_text(hjust = 0.5)) # Correctly centering the title
ggsave("todaypartisans.jpeg", width = 6, height = 6, units = "in", dpi = 500)


# Load necessary libraries
library(ggplot2)
library(dplyr)
library(scales)

survey_data <- data.frame(
  Question = rep(c('Majority\n Violates\n Constitution', 'Majority\n Ignores\n Minority', 'Majority\n Bans\n Speech'), each = 4),
  Year = rep(c('1978-1979', '2024'), times = 6),
  Group = c(rep('Mass Public', 2), rep('Leaders', 2)),
  No = c(49, 55, 67, 78, 75, 77, 88, 88, 49, 68, 67, 80),  
  Yes = c(22, 25, 14, 7, 10, 8, 6, 2, 23, 13, 15, 4),   
  Neither = c(29, 20, 19, 15, 15, 16, 6, 10, 28, 18, 17, 16) 
)



# Reshape for plotting
survey_data_long <- survey_data %>% 
  gather(key = "Response", value = "Percentage", No:Neither)

# Create a summarized version for labeling
label_data <- survey_data_long %>%
  group_by(Question, Year, Group, Response) %>%
  summarize(Percentage = sum(Percentage))

# Custom color palette
colors <- c("No" = "#66c2a5", "Yes" = "#fc8d62", "Neither" = "#8da0cb")

# Plot
gg <- ggplot(survey_data_long, aes(fill=Response, y=Percentage, x=factor(Question))) + 
  geom_bar(position="fill", stat="identity") +
  facet_grid(Group~Year, scales = "free_x", space = "free") +
  coord_flip() +
  scale_fill_manual(values=colors) +
  theme_minimal() +
  theme(legend.position="bottom",
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank()) +
  labs(x = "", y = "", fill = "Response", 
       title = "Support for Minority Political Rights Across Time and Groups")

# Adding the percentage labels for all responses
# Adjusting position for 'Yes' and 'Neither' responses
gg <- gg + geom_text(data = label_data,
                     aes(label = paste0(Percentage, "%"), y = ifelse(Response == "Yes", Percentage + 10, ifelse(Response == "Neither", Percentage +10, Percentage))),
                     position = position_fill(vjust = 0.5),
                     color = "white", size = 3.5)

# Display the plot
print(gg)

ggsave("timeplot.jpeg", width = 6, height = 6, units = "in", dpi = 500)




### CONJOINT


d1 <- d1 %>%
  mutate(
    # Classify 'Nat_elect' and 'Local_elect' for Trial 1
    Nat_elect_in_party_1A = if_else((InParty == "Republican" & grepl("Republicans", Nat_elect_QD_1A)) | 
                                      (InParty == "Democrat" & grepl("Democrats", Nat_elect_QD_1A)), 
                                    "In-party", "Out-party"),
    Local_elect_in_party_1A = if_else((InParty == "Republican" & grepl("Republicans", Local_elect_QD_1A)) | 
                                        (InParty == "Democrat" & grepl("Democrats", Local_elect_QD_1A)), 
                                      "In-party", "Out-party"),
    
    # Classify for Trial 2
    Nat_elect_in_party_2A = if_else((InParty == "Republican" & grepl("Republicans", Nat_elect_QD_2A)) | 
                                      (InParty == "Democrat" & grepl("Democrats", Nat_elect_QD_2A)), 
                                    "In-party", "Out-party"),
    Local_elect_in_party_2A = if_else((InParty == "Republican" & grepl("Republicans", Local_elect_QD_2A)) | 
                                        (InParty == "Democrat" & grepl("Democrats", Local_elect_QD_2A)), 
                                      "In-party", "Out-party"),
    
    # Classify for Trial 3
    Nat_elect_in_party_3A = if_else((InParty == "Republican" & grepl("Republicans", Nat_elect_QD_3A)) | 
                                      (InParty == "Democrat" & grepl("Democrats", Nat_elect_QD_3A)), 
                                    "In-party", "Out-party"),
    Local_elect_in_party_3A = if_else((InParty == "Republican" & grepl("Republicans", Local_elect_QD_3A)) | 
                                        (InParty == "Democrat" & grepl("Democrats", Local_elect_QD_3A)), 
                                      "In-party", "Out-party"),
    
    # Repeat the above steps for the 'B' versions of each trial
    Nat_elect_in_party_1B = if_else((InParty == "Republican" & grepl("Republicans", Nat_elect_QD_1B)) | 
                                      (InParty == "Democrat" & grepl("Democrats", Nat_elect_QD_1B)), 
                                    "In-party", "Out-party"),
    Local_elect_in_party_1B = if_else((InParty == "Republican" & grepl("Republicans", Local_elect_QD_1B)) | 
                                        (InParty == "Democrat" & grepl("Democrats", Local_elect_QD_1B)), 
                                      "In-party", "Out-party"),
    Nat_elect_in_party_2B = if_else((InParty == "Republican" & grepl("Republicans", Nat_elect_QD_2B)) | 
                                      (InParty == "Democrat" & grepl("Democrats", Nat_elect_QD_2B)), 
                                    "In-party", "Out-party"),
    Local_elect_in_party_2B = if_else((InParty == "Republican" & grepl("Republicans", Local_elect_QD_2B)) | 
                                        (InParty == "Democrat" & grepl("Democrats", Local_elect_QD_2B)), 
                                      "In-party", "Out-party"),
    Nat_elect_in_party_3B = if_else((InParty == "Republican" & grepl("Republicans", Nat_elect_QD_3B)) | 
                                      (InParty == "Democrat" & grepl("Democrats", Nat_elect_QD_3B)), 
                                    "In-party", "Out-party"),
    Local_elect_in_party_3B = if_else((InParty == "Republican" & grepl("Republicans", Local_elect_QD_3B)) | 
                                        (InParty == "Democrat" & grepl("Democrats", Local_elect_QD_3B)), 
                                      "In-party", "Out-party")
  )



d1 <- d1 %>%
  # Recode 'Nat_elect' for all trials (1A, 1B, 2A, 2B, 3A, 3B)
  mutate(
    Nat_elect_QD_1A = case_when(
      Nat_elect_in_party_1A == "In-party" & grepl("take control of Congress", Nat_elect_QD_1A) ~ "In-party wins the Presidency and takes control of Congress.",
      Nat_elect_in_party_1A == "In-party" & grepl("but Congress is divided", Nat_elect_QD_1A) ~ "In-party wins the presidency but Congress is divided.",
      Nat_elect_in_party_1A == "Out-party" & grepl("but Congress is divided", Nat_elect_QD_1A) ~ "Out-party wins the Presidency but Congress is divided.",
      Nat_elect_in_party_1A == "Out-party" & grepl("take control of Congress", Nat_elect_QD_1A) ~ "Out-party wins the Presidency and takes control of Congress.",
      TRUE ~ Nat_elect_QD_1A
    ),
    Nat_elect_QD_1B = case_when(
      Nat_elect_in_party_1B == "In-party" & grepl("take control of Congress", Nat_elect_QD_1B) ~ "In-party wins the Presidency and takes control of Congress.",
      Nat_elect_in_party_1B == "In-party" & grepl("but Congress is divided", Nat_elect_QD_1B) ~ "In-party wins the presidency but Congress is divided.",
      Nat_elect_in_party_1B == "Out-party" & grepl("but Congress is divided", Nat_elect_QD_1B) ~ "Out-party wins the Presidency but Congress is divided.",
      Nat_elect_in_party_1B == "Out-party" & grepl("take control of Congress", Nat_elect_QD_1B) ~ "Out-party wins the Presidency and takes control of Congress.",
      TRUE ~ Nat_elect_QD_1B
    ),
    Nat_elect_QD_2A = case_when(
      Nat_elect_in_party_2A == "In-party" & grepl("take control of Congress", Nat_elect_QD_2A) ~ "In-party wins the Presidency and takes control of Congress.",
      Nat_elect_in_party_2A == "In-party" & grepl("but Congress is divided", Nat_elect_QD_2A) ~ "In-party wins the presidency but Congress is divided.",
      Nat_elect_in_party_2A == "Out-party" & grepl("but Congress is divided", Nat_elect_QD_2A) ~ "Out-party wins the Presidency but Congress is divided.",
      Nat_elect_in_party_2A == "Out-party" & grepl("take control of Congress", Nat_elect_QD_2A) ~ "Out-party wins the Presidency and takes control of Congress.",
      TRUE ~ Nat_elect_QD_1A
    ),
    Nat_elect_QD_2B = case_when(
      Nat_elect_in_party_2B == "In-party" & grepl("take control of Congress", Nat_elect_QD_2B) ~ "In-party wins the Presidency and takes control of Congress.",
      Nat_elect_in_party_2B == "In-party" & grepl("but Congress is divided", Nat_elect_QD_2B) ~ "In-party wins the presidency but Congress is divided.",
      Nat_elect_in_party_2B == "Out-party" & grepl("but Congress is divided", Nat_elect_QD_2B) ~ "Out-party wins the Presidency but Congress is divided.",
      Nat_elect_in_party_2B == "Out-party" & grepl("take control of Congress", Nat_elect_QD_2B) ~ "Out-party wins the Presidency and takes control of Congress.",
      TRUE ~ Nat_elect_QD_2B
    ),
    Nat_elect_QD_3A = case_when(
      Nat_elect_in_party_3A == "In-party" & grepl("take control of Congress", Nat_elect_QD_3A) ~ "In-party wins the Presidency and takes control of Congress.",
      Nat_elect_in_party_3A == "In-party" & grepl("but Congress is divided", Nat_elect_QD_3A) ~ "In-party wins the presidency but Congress is divided.",
      Nat_elect_in_party_3A == "Out-party" & grepl("but Congress is divided", Nat_elect_QD_3A) ~ "Out-party wins the Presidency but Congress is divided.",
      Nat_elect_in_party_3A == "Out-party" & grepl("take control of Congress", Nat_elect_QD_3A) ~ "Out-party wins the Presidency and takes control of Congress.",
      TRUE ~ Nat_elect_QD_3A
    ),
    Nat_elect_QD_3B = case_when(
      Nat_elect_in_party_3B == "In-party" & grepl("take control of Congress", Nat_elect_QD_3B) ~ "In-party wins the Presidency and takes control of Congress.",
      Nat_elect_in_party_3B == "In-party" & grepl("but Congress is divided", Nat_elect_QD_3B) ~ "In-party wins the presidency but Congress is divided.",
      Nat_elect_in_party_3B == "Out-party" & grepl("but Congress is divided", Nat_elect_QD_3B) ~ "Out-party wins the Presidency but Congress is divided.",
      Nat_elect_in_party_3B == "Out-party" & grepl("take control of Congress", Nat_elect_QD_3B) ~ "Out-party wins the Presidency and takes control of Congress.",
      TRUE ~ Nat_elect_QD_3B
    ),
    # Recode 'Local_elect' for all trials (1A, 1B, 2A, 2B, 3A, 3B)
    Local_elect_QD_1A = case_when(
      Local_elect_in_party_1A == "In-party" & grepl("take control", Local_elect_QD_1A) ~ "In-party takes control of your local governing board.",
      Local_elect_in_party_1A == "Out-party" & grepl("take control", Local_elect_QD_1A) ~ "Out-party takes control of your local governing board.",
      TRUE ~ Local_elect_QD_1A
    ),
    Local_elect_QD_1B = case_when(
      Local_elect_in_party_1B == "In-party" & grepl("take control", Local_elect_QD_1B) ~ "In-party takes control of your local governing board.",
      Local_elect_in_party_1B == "Out-party" & grepl("take control", Local_elect_QD_1B) ~ "Out-party takes control of your local governing board.",
      TRUE ~ Local_elect_QD_1B
    ),
    Local_elect_QD_2A = case_when(
      Local_elect_in_party_2A == "In-party" & grepl("take control", Local_elect_QD_2A) ~ "In-party takes control of your local governing board.",
      Local_elect_in_party_2A == "Out-party" & grepl("take control", Local_elect_QD_2A) ~ "Out-party takes control of your local governing board.",
      TRUE ~ Local_elect_QD_2A
    ),
    Local_elect_QD_2B = case_when(
      Local_elect_in_party_2B == "In-party" & grepl("take control", Local_elect_QD_2B) ~ "In-party takes control of your local governing board.",
      Local_elect_in_party_2B == "Out-party" & grepl("take control", Local_elect_QD_2B) ~ "Out-party takes control of your local governing board.",
      TRUE ~ Local_elect_QD_2B
    ),
    Local_elect_QD_3A = case_when(
      Local_elect_in_party_3A == "In-party" & grepl("take control", Local_elect_QD_3A) ~ "In-party takes control of your local governing board.",
      Local_elect_in_party_3A == "Out-party" & grepl("take control", Local_elect_QD_3A) ~ "Out-party takes control of your local governing board.",
      TRUE ~ Local_elect_QD_3A
    ),
    Local_elect_QD_3B = case_when(
      Local_elect_in_party_3B == "In-party" & grepl("take control", Local_elect_QD_3B) ~ "In-party takes control of your local governing board.",
      Local_elect_in_party_3B == "Out-party" & grepl("take control", Local_elect_QD_3B) ~ "Out-party takes control of your local governing board.",
      TRUE ~ Local_elect_QD_3B
    ),
  )

d1 <- d1 %>%
  mutate(
    Leg_change_QD_1A = case_when(
      grepl("bans a .* candidate from competing in state and local campaigns", Leg_change_QD_1A) ~ "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies.",
      grepl("restricts a .* candidate from advertising in state and local campaigns", Leg_change_QD_1A) ~ "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies.",
      grepl("bans all .* from competing in state and local campaigns", Leg_change_QD_1A) ~ "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("bans some .* from competing in state and local campaigns", Leg_change_QD_1A) ~ "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("recommends a non-binding cap on the number of campaign volunteers", Leg_change_QD_1A) ~ "The state legislature recommends a non-binding cap on the number of campaign volunteers.",
      TRUE ~ Leg_change_QD_1A
    ),
    Leg_change_QD_1B = case_when(
      grepl("bans a .* candidate from competing in state and local campaigns", Leg_change_QD_1B) ~ "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies.",
      grepl("restricts a .* candidate from advertising in state and local campaigns", Leg_change_QD_1B) ~ "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies.",
      grepl("bans all .* from competing in state and local campaigns", Leg_change_QD_1B) ~ "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("bans some .* from competing in state and local campaigns", Leg_change_QD_1B) ~ "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("recommends a non-binding cap on the number of campaign volunteers", Leg_change_QD_1B) ~ "The state legislature recommends a non-binding cap on the number of campaign volunteers.",
      TRUE ~ Leg_change_QD_1B
    ),
    Leg_change_QD_2A = case_when(
      grepl("bans a .* candidate from competing in state and local campaigns", Leg_change_QD_2A) ~ "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies.",
      grepl("restricts a .* candidate from advertising in state and local campaigns", Leg_change_QD_2A) ~ "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies.",
      grepl("bans all .* from competing in state and local campaigns", Leg_change_QD_2A) ~ "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("bans some .* from competing in state and local campaigns", Leg_change_QD_2A) ~ "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("recommends a non-binding cap on the number of campaign volunteers", Leg_change_QD_2A) ~ "The state legislature recommends a non-binding cap on the number of campaign volunteers.",
      TRUE ~ Leg_change_QD_2A
    ),
    Leg_change_QD_2B = case_when(
      grepl("bans a .* candidate from competing in state and local campaigns", Leg_change_QD_2B) ~ "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies.",
      grepl("restricts a .* candidate from advertising in state and local campaigns", Leg_change_QD_2B) ~ "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies.",
      grepl("bans all .* from competing in state and local campaigns", Leg_change_QD_2B) ~ "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("bans some .* from competing in state and local campaigns", Leg_change_QD_2B) ~ "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("recommends a non-binding cap on the number of campaign volunteers", Leg_change_QD_2B) ~ "The state legislature recommends a non-binding cap on the number of campaign volunteers.",
      TRUE ~ Leg_change_QD_2B
    ),
    Leg_change_QD_3A = case_when(
      grepl("bans a .* candidate from competing in state and local campaigns", Leg_change_QD_3A) ~ "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies.",
      grepl("restricts a .* candidate from advertising in state and local campaigns", Leg_change_QD_3A) ~ "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies.",
      grepl("bans all .* from competing in state and local campaigns", Leg_change_QD_3A) ~ "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("bans some .* from competing in state and local campaigns", Leg_change_QD_3A) ~ "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("recommends a non-binding cap on the number of campaign volunteers", Leg_change_QD_3A) ~ "The state legislature recommends a non-binding cap on the number of campaign volunteers.",
      TRUE ~ Leg_change_QD_3A
    ),
    Leg_change_QD_3B = case_when(
      grepl("bans a .* candidate from competing in state and local campaigns", Leg_change_QD_3B) ~ "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies.",
      grepl("restricts a .* candidate from advertising in state and local campaigns", Leg_change_QD_3B) ~ "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies.",
      grepl("bans all .* from competing in state and local campaigns", Leg_change_QD_3B) ~ "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("bans some .* from competing in state and local campaigns", Leg_change_QD_3B) ~ "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies.",
      grepl("recommends a non-binding cap on the number of campaign volunteers", Leg_change_QD_3B) ~ "The state legislature recommends a non-binding cap on the number of campaign volunteers.",
      TRUE ~ Leg_change_QD_3B
    )
  )

d1$Sal_change_QD_1A <- gsub("Your employer  raises your pay by 5%.", 
                            "Your employer raises your pay by 5%.", 
                            d1$Sal_change_QD_1A)
###reshape our data from wide to long

d<-mutate(d1, ID = row_number())

################
list1 <- list(
  NatElect = list(
    ~ Nat_elect_QD_1A + Nat_elect_QD_2A + Nat_elect_QD_3A ,
    ~ Nat_elect_QD_1B + Nat_elect_QD_2B + Nat_elect_QD_3B ),
  LocalElect = list(
    ~ Local_elect_QD_1A + Local_elect_QD_2A + Local_elect_QD_3A ,
    ~ Local_elect_QD_1B + Local_elect_QD_2B + Local_elect_QD_3B),
  LegChange = list(
    ~ Leg_change_QD_1A+ Leg_change_QD_2A +Leg_change_QD_3A ,
    ~ Leg_change_QD_1B+ Leg_change_QD_2B+Leg_change_QD_3B),
  SalChange = list(
    ~ Sal_change_QD_1A+Sal_change_QD_2A+Sal_change_QD_3A,
    ~ Sal_change_QD_1B+Sal_change_QD_2B+Sal_change_QD_3B)
  )
# task variables
list2 <- list(choice = ~ Conjoint1_SC + Conjoint2_SC + Conjoint3_SC )

library(cregg)
# perform reshape
str(long <- cj_tidy(d,
                    profile_variables = list1,
                    task_variables = list2,
                    id = ~ ID))
stopifnot(nrow(long) == nrow(d)*3*2)

# recode outcome so it is coded sensibly
long$chosen <- ifelse((long$profile == "A" & long$choice == 1) | 
                        (long$profile == "B" & long$choice == 0), 1, 0)

long <- subset(long, long$chosen != "NA")
# use for analysis


long$Presidential_Election_Outcome_2024 <- factor(long$NatElect, levels = c("Out-party wins the Presidency and takes control of Congress.",
                                                  "Out-party wins the Presidency but Congress is divided.",
                                                  "In-party wins the presidency but Congress is divided.",
                                                  "In-party wins the Presidency and takes control of Congress."))

long$Local_Election_Outcome_2024 <- factor(long$LocalElect, levels = c("Out-party takes control of your local governing board.",
                                                      "Your local governing board is evenly split between Democrats and Republicans.",
                                                      "In-party takes control of your local governing board."))

long$Antidemocratic_Legislation <- factor(long$LegChange, levels = c("The state legislature recommends a non-binding cap on the number of campaign volunteers.",
                                                    "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies.",
                                                    "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies.",
                                                    "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies.",
                                                    "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies."))

long$Salary_Change <- factor(long$SalChange, levels = c("Your employer leaves your pay unchanged.",
                                                    "Your employer cuts your pay by 20%.",
                                                    "Your employer cuts your pay by 10%.",
                                                    "Your employer cuts your pay by 5%.",
                                                    "Your employer raises your pay by 5%.",
                                                    "Your employer raises your pay by 10%.",
                                                    "Your employer raises your pay by 20%."))



long$ID <- as.factor(long$ID)

#####order factors######
long <- within(long, Presidential_Election_Outcome_2024 <- relevel(Presidential_Election_Outcome_2024, ref = "Out-party wins the Presidency and takes control of Congress."))
long <- within(long, Local_Election_Outcome_2024 <- relevel(Local_Election_Outcome_2024, ref = "Your local governing board is evenly split between Democrats and Republicans."))
long <- within(long, Antidemocratic_Legislation <- relevel(Antidemocratic_Legislation, ref = "The state legislature recommends a non-binding cap on the number of campaign volunteers."))
long <- within(long, Salary_Change <- relevel(Salary_Change, ref = "Your employer leaves your pay unchanged."))






#amce clustered standard errors, including experimentally treated# 
f1<-cj(long, chosen ~ Presidential_Election_Outcome_2024 + Local_Election_Outcome_2024 + Antidemocratic_Legislation  + Salary_Change, id = ~ ID)
plot(f1, xlab = "Estimated AMCE (Change in Probability of Profile Selected)", level_order = c("descending"))
library(cjoint)
detach("package:cregg", unload = TRUE)
f1Main<-amce(chosen ~Presidential_Election_Outcome_2024 + Local_Election_Outcome_2024 + Antidemocratic_Legislation  + Salary_Change, data= long, cluster=TRUE, respondent.id= "ID")





summary(f1Main)

######## PLOT FOR AMCE
# Create vectors for the attributes, levels, estimates, and standard errors
attributes <- c(
  "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation",
  "Local Election Outcome 2024", "Local Election Outcome 2024",
  "Presidential Election Outcome 2024", "Presidential Election Outcome 2024", "Presidential Election Outcome 2024",
  "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change"
)

levels <- c(
  "Restricts out-party candidate advertising", "Bans out-party candidate", "Bans some out-party members", "Bans all out-party members",
  "Out-party takes local board", "In-party takes local board",
  "Out-party wins Presidency, divided Congress", "In-party wins Presidency, divided Congress", "In-party wins Presidency & Congress",
  "Employer cuts pay by 20%", "Employer cuts pay by 10%", "Employer cuts pay by 5%",
  "Employer raises pay by 5%", "Employer raises pay by 10%", "Employer raises pay by 20%"
)

estimates <- c(-0.017408, -0.015756, -0.020168, -0.081401,
               -0.092204, 0.021732,
               0.099605, 0.275375, 0.342706,
               -0.250312, -0.158960, -0.053166,
               0.080555, 0.113682, 0.179243)

std_errs <- c(0.019007, 0.018977, 0.018737, 0.020005,
              0.014427, 0.014749,
              0.018093, 0.017895, 0.018260,
              0.023356, 0.023789, 0.024399,
              0.024000, 0.023451, 0.023516)



# Calculate the 95% confidence intervals
lower_bounds <- estimates - (1.96 * std_errs)
upper_bounds <- estimates + (1.96 * std_errs)

# Combine into a data frame
results_df <- data.frame(
  Attribute = attributes,
  Level = levels,
  Estimate = estimates,
  StdErr = std_errs,
  LowerCI = lower_bounds,
  UpperCI = upper_bounds
)

# View the data frame
print(results_df)

library(ggplot2)
library(dplyr)

# Assuming results_df is your original data frame
# Add the 'Significant' column based on the 95% confidence interval
results_df$Significant <- with(results_df, LowerCI > 0 | UpperCI < 0)

# Update baseline levels with the correct labels
baseline_levels <- data.frame(
  Attribute = c("Antidemocratic Legislation", "Local Election Outcome 2024", 
                "Presidential Election Outcome 2024", "Salary Change"),
  Level = c("Non-binding cap on campaign volunteers", "Local board evenly divided", 
            "Out-party wins Presidency & Congress", "Employer leaves pay unchanged"),
  Estimate = 0,
  StdErr = 0,
  LowerCI = 0,
  UpperCI = 0,
  Significant = TRUE
)

# Combine baseline levels with results_df
results_with_baseline <- rbind(results_df, baseline_levels)


# Create the plot
ggplot(results_with_baseline, aes(x = reorder(Level, Estimate), y = Estimate, fill = Significant)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("grey", NA)) +
  coord_flip() +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), width = 0.4, color = "black") +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "AMCE Estimate", title = "") +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_rect(fill = "white", colour = "white"), 
    axis.line.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.line = element_line(colour = "black") 
  )

# Save the plot
ggsave("genpopamce.jpeg", width = 6, height = 6, units = "in", dpi = 500)


### PLOT FOR MARGINAL MEANS

library(cregg)

#mm1 <- mm(long, chosen ~ Presidential_Election_Outcome_2024 + Local_Election_Outcome_2024 + Antidemocratic_Legislation  + Salary_Change, id = ~ ID)
#p <- plot(mm1, vline = 0.5, colors="black", text.size = 10, plot.theme = theme_bw())
#p



#mm1 <- mm(long, chosen ~ Antidemocratic_Legislation+ Local_Election_Outcome_2024 +  Presidential_Election_Outcome_2024  + Salary_Change, id = ~ ID)




mm_results <- mm(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                   Presidential_Election_Outcome_2024 + Salary_Change, id = ~ ID)

# Assuming mm_results is already your marginal means data frame
mm_data_frame <- mm_results

# Filter to keep only relevant columns
mm_data_frame <- mm_data_frame[, c("feature", "level", "estimate", "std.error", "lower", "upper")]

# Rename the columns for clarity
colnames(mm_data_frame) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI")
mm_data_frame$Attribute <- gsub("_", " ", mm_data_frame$Attribute) # Replace underscores with spaces

# Named vector for new labels with correct current levels
new_labels <- c(
  "The state legislature recommends a non-binding cap on the number of campaign volunteers." = "Non-binding cap on campaign volunteers",
  "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies." = "Restricts out-party candidate advertising",
  "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies." = "Bans out-party candidate",
  "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies." = "Bans some out-party members",
  "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies." = "Bans all out-party members",
  "Your local governing board is evenly split between Democrats and Republicans." = "Local board evenly divided",
  "Out-party takes control of your local governing board." = "Out-party takes local board",
  "In-party takes control of your local governing board." = "In-party takes local board",
  "Out-party wins the Presidency and takes control of Congress." = "Out-party wins Presidency & Congress",
  "Out-party wins the Presidency but Congress is divided." = "Out-party wins Presidency, divided Congress",
  "In-party wins the presidency but Congress is divided." = "In-party wins Presidency, divided Congress",
  "In-party wins the Presidency and takes control of Congress." = "In-party wins Presidency & Congress",
  "Your employer leaves your pay unchanged." = "Employer leaves pay unchanged",
  "Your employer cuts your pay by 20%." = "Employer cuts pay by 20%",
  "Your employer cuts your pay by 10%." = "Employer cuts pay by 10%",
  "Your employer cuts your pay by 5%." = "Employer cuts pay by 5%",
  "Your employer raises your pay by 5%." = "Employer raises pay by 5%",
  "Your employer raises your pay by 10%." = "Employer raises pay by 10%",
  "Your employer raises your pay by 20%." = "Employer raises pay by 20%"
)

# Create the plot with enhanced aesthetics and new level labels
ggplot(mm_data_frame, aes(x = reorder(Level, Estimate), y = Estimate)) +
  geom_point(aes(color = Estimate), size = 3) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), width = 0.4, color = "black") +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "none"
  ) +
  scale_color_gradient(low = "black", high = "black") +
  scale_x_discrete(labels = new_labels) # Apply new labels

ggsave("genpopmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)

## Marginal means partisans:



long$InParty <- as.factor(long$InParty)

mm_resultsPID <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                   Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ InParty)

mm_resultsPID_df <- as.data.frame(mm_resultsPID)

# Ensure the dataframe has the necessary columns
mm_resultsPID_df <- mm_resultsPID_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "InParty")]

# Rename the columns for clarity
colnames(mm_resultsPID_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "InParty")
mm_resultsPID_df$Attribute <- gsub("_", " ", mm_resultsPID_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsPID_df$Level <- factor(mm_resultsPID_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsPID_df, aes(x = reorder(Level, Estimate), y = Estimate, color = InParty)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Democrat" = "blue", "Republican" = "red")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("partisanmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)


# Perform ANOVA for differences between partisan groups
anova_result <- cj_anova(chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                           Presidential_Election_Outcome_2024 + Salary_Change, 
                         id = ~ID, by = ~InParty, data = long)

# Print the ANOVA result
print(anova_result)

## Marginal means Education:



long$CollegeEducation <- as.factor(ifelse(long$CollegeEducation0 == 1, "Yes", "No"))

mm_resultsCollege <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                      Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ CollegeEducation)

mm_resultsCollege_df <- as.data.frame(mm_resultsCollege)

# Ensure the dataframe has the necessary columns
mm_resultsCollege_df <- mm_resultsCollege_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "CollegeEducation")]

# Rename the columns for clarity
colnames(mm_resultsCollege_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "CollegeEducation")
mm_resultsCollege_df$Attribute <- gsub("_", " ", mm_resultsCollege_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsCollege_df$Level <- factor(mm_resultsCollege_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsCollege_df, aes(x = reorder(Level, Estimate), y = Estimate, color = CollegeEducation)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Yes" = "black", "No" = "grey")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("educationmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)


## Marginal means StrongIdeologue:


long$StrongIdeologue <- as.factor(ifelse(as.numeric(long$StrongIdeologue0 == 1), "Yes", "No"))

mm_resultsIdeologue <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                          Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ StrongIdeologue)

mm_resultsIdeologue_df <- as.data.frame(mm_resultsIdeologue)

# Ensure the dataframe has the necessary columns
mm_resultsIdeologue_df <- mm_resultsIdeologue_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "StrongIdeologue")]

# Rename the columns for clarity
colnames(mm_resultsIdeologue_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "StrongIdeologue")
mm_resultsIdeologue_df$Attribute <- gsub("_", " ", mm_resultsIdeologue_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsIdeologue_df$Level <- factor(mm_resultsIdeologue_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsIdeologue_df, aes(x = reorder(Level, Estimate), y = Estimate, color = StrongIdeologue)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Yes" = "black", "No" = "grey")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("ideologuemm.jpeg", width = 6, height = 6, units = "in", dpi = 500)

### REDONE GEN POP AMCE GRAPH:

# Create vectors for the attributes, levels, estimates, and standard errors
attributes <- c(
  "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation",
  "Local Election Outcome 2024", "Local Election Outcome 2024",
  "Presidential Election Outcome 2024", "Presidential Election Outcome 2024", "Presidential Election Outcome 2024",
  "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change"
)

levels <- c(
  "Restricts out-party candidate advertising", "Bans out-party candidate", "Bans some out-party members", "Bans all out-party members",
  "Out-party takes local board", "In-party takes local board",
  "Out-party wins Presidency, divided Congress", "In-party wins Presidency, divided Congress", "In-party wins Presidency & Congress",
  "Employer cuts pay by 20%", "Employer cuts pay by 10%", "Employer cuts pay by 5%",
  "Employer raises pay by 5%", "Employer raises pay by 10%", "Employer raises pay by 20%"
)

estimates <- c(-0.017408, -0.015756, -0.020168, -0.081401,
               -0.092204, 0.021732,
               0.099605, 0.275375, 0.342706,
               -0.250312, -0.158960, -0.053166,
               0.080555, 0.113682, 0.179243)

std_errs <- c(0.019007, 0.018977, 0.018737, 0.020005,
              0.014427, 0.014749,
              0.018093, 0.017895, 0.018260,
              0.023356, 0.023789, 0.024399,
              0.024000, 0.023451, 0.023516)

# Calculate the 95% confidence intervals
lower_bounds <- estimates - (1.96 * std_errs)
upper_bounds <- estimates + (1.96 * std_errs)

# Combine into a data frame
results_df <- data.frame(
  Attribute = attributes,
  Level = levels,
  Estimate = estimates,
  StdErr = std_errs,
  LowerCI = lower_bounds,
  UpperCI = upper_bounds
)

# Add 'Significant' column based on the 95% confidence interval
results_df$Significant <- with(results_df, LowerCI > 0 | UpperCI < 0)

# Update baseline levels labels
baseline_levels <- data.frame(
  Attribute = c("Antidemocratic Legislation", "Presidential Election Outcome 2024", 
                "Local Election Outcome 2024", "Salary Change"),
  Level = c("Non-binding cap on campaign volunteers", "Out-party wins Presidency & Congress", 
            "Local board evenly divided", "Employer leaves pay unchanged"),
  Estimate = 0,
  StdErr = 0,
  LowerCI = 0,
  UpperCI = 0,
  Significant = FALSE
)

# Add line breaks to baseline levels for better visualization
baseline_levels$Level <- gsub("Non-binding cap on campaign volunteers", "Non-binding cap on\ncampaign volunteers", baseline_levels$Level)
baseline_levels$Level <- gsub("Out-party wins Presidency & Congress", "Out-party wins\nPresidency & Congress", baseline_levels$Level)
baseline_levels$Level <- gsub("Local board evenly divided", "Local board\nevenly divided", baseline_levels$Level)
baseline_levels$Level <- gsub("Employer leaves pay unchanged", "Pay unchanged", baseline_levels$Level)

# Combine baseline levels with results_df
results_with_baseline <- rbind(results_df, baseline_levels)

# Specify the order of the attributes
results_with_baseline$Attribute <- factor(results_with_baseline$Attribute, 
                                          levels = c("Antidemocratic Legislation", "Presidential Election Outcome 2024", "Local Election Outcome 2024", "Salary Change"))

# Add line breaks to the levels for better visualization
results_with_baseline$Level <- gsub("Restricts out-party candidate advertising", "Restricts out-party\ncandidate advertising", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Bans out-party candidate", "Bans out-party\ncandidate", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Bans some out-party members", "Bans some\nout-party members", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Bans all out-party members", "Bans all\nout-party members", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Out-party wins Presidency, divided Congress", "Out-party wins Presidency,\ndivided Congress", results_with_baseline$Level)
results_with_baseline$Level <- gsub("In-party wins Presidency, divided Congress", "In-party wins Presidency,\ndivided Congress", results_with_baseline$Level)
results_with_baseline$Level <- gsub("In-party wins Presidency & Congress", "In-party wins Presidency\n& Congress", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Out-party takes local board", "Out-party takes\nlocal board", results_with_baseline$Level)
results_with_baseline$Level <- gsub("In-party takes local board", "In-party takes\nlocal board", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Employer cuts pay by 20%", "Pay cut by 20%", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Employer cuts pay by 10%", "Pay cut by 10%", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Employer cuts pay by 5%", "Pay cut by 5%", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Employer raises pay by 5%", "Pay raised by 5%", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Employer raises pay by 10%", "Pay raised by 10%", results_with_baseline$Level)
results_with_baseline$Level <- gsub("Employer raises pay by 20%", "Pay raised by 20%", results_with_baseline$Level)

# Define the desired order of levels
desired_order <- rev(c(
  "Non-binding cap on\ncampaign volunteers",
  "Restricts out-party\ncandidate advertising",
  "Bans out-party\ncandidate",
  "Bans some\nout-party members",
  "Bans all\nout-party members",
  "In-party wins Presidency\n& Congress",
  "In-party wins Presidency,\ndivided Congress",
  "Out-party wins Presidency,\ndivided Congress",
  "Out-party wins\nPresidency & Congress",
  "Local board\nevenly divided",
  "In-party takes\nlocal board",
  "Out-party takes\nlocal board",
  "Pay unchanged",
  "Pay cut by 20%",
  "Pay cut by 10%",
  "Pay cut by 5%",
  "Pay raised by 5%",
  "Pay raised by 10%",
  "Pay raised by 20%"
))

# Reorder levels according to desired order
results_with_baseline$Level <- factor(results_with_baseline$Level, levels = desired_order)

# Create the plot
library(ggplot2)
ggplot(results_with_baseline, aes(x = Level, y = Estimate, fill = Significant)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("grey", NA)) +
  coord_flip() +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), width = 0.4, color = "black") +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "AMCE Estimate", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 12, color = "black"),          
    axis.text.y = element_text(size = 12, color = "black"),          
    axis.title.x = element_blank(),
    axis.title.y = element_text(size = 14, color = "black"),         
    strip.text = element_text(size = 13, angle = 0, color = "black"), 
    panel.grid.major = element_blank(),             
    panel.grid.minor = element_blank(),             
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.text = element_text(size = 12, color = "black"),          
    legend.title = element_text(size = 12, color = "black"),
    legend.position = "none"
  ) 

# Save the plot
ggsave("genpopamce.jpeg", width = 6, height = 11, units = "in", dpi = 500)

